#!/usr/bin/perl

use strict;
use Cwd;

sub usage()
{
	print <<END;
usage: $0 [optional_directory]
	traverses current (or, if present, optional_directory) and all
	subdirectories, converting those that contain a file
	"mimetype" to an epub
END
	exit(1);
}

if (scalar(@ARGV) > 1) {
	usage;
}

sub ImplodeDir()	# implode current directory to curdir.epub
{
	my $thisdir = cwd;
	my $epub_file = $thisdir . ".epub";

	if (! -e "mimetype") {
		print "error: cannot locate file '$thisdir/mimetype'\n";
		return;
	}

	if (-e $epub_file) {
		if (unlink($epub_file) != 1) {
			print  "error: unable to remove $epub_file\n";
			return;
		}
	}

	my $zip_results = `zip -X -q -0 "$epub_file" mimetype`;
	$zip_results = `zip -q -r "$epub_file" * -x mimetype`;


	if (-e $epub_file) {
		print "created '$epub_file'\n";
	} else {
		die "error: failed to create '$epub_file'\n";
	}
} # ImplodeDir

sub SearchDir()		# look for mimetype in current or subdirs
{
	if (-f "mimetype") {
		ImplodeDir();
		return;
	}

	my $cwd = cwd;
	my @files;
	if (opendir(DIR,$cwd)) {
		@files = readdir(DIR);
		closedir(DIR);
	} else {
		die "Unable to read directory $cwd\n";
	}

	while (@files) {
		my $thisdir = shift(@files);
		if ($thisdir =~ m!^\.!) {	# ignore relative and hidden dirs
			next;
		}
		if (-d $thisdir) {		# recurse into subdir
			chdir($thisdir);
			SearchDir();
			chdir($cwd);
		}
	}
} # SearchDir


my $dir = cwd;
if (scalar(@ARGV) > 0) {
	$dir = shift(@ARGV);
	$dir =~ s!\\!/!g;	# convert to Perl path separators, if necessary
	$dir =~ s!/$!!g;	# drop trailing path separator, if necessary
}

my $startingdir = cwd;

chdir($dir);
SearchDir();
chdir($startingdir);

exit(0);
